#include "widget.h"
#include "ui_widget.h"
#include <QTimer>
#include <QMouseEvent>
#include <QDebug>


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //开启定时器
    //单位毫秒
    //第一个timer的id
    timerId_1 = startTimer(1000);

    //第二个timer的id
    timerId_2 = startTimer(2000);

    //创建定时器对象
    QTimer * timer1 = new QTimer(this);
    timer1->start(500);

    //每隔4秒会抛出一个信号
    connect(timer1, &QTimer::timeout, this, [=](){
        static int num3 = 1;
        ui->label_timer_per4sec->setText(QString::number(num3++));
    });



    bool stopFlag = false;

    //点击暂停按钮，停止定时器
    connect(ui->pushButton, &QPushButton::clicked, this, [&](){
        stopFlag ? timer1->start() : timer1->stop();
        //修改这个变量值，需要lambda使用引用传递
        stopFlag = !stopFlag;
    });

    //给label添加事件过滤器，做更高级的拦截操作
    //1. 给控件安装过滤器
    ui->label->installEventFilter(this);
}

Widget::~Widget()
{
    delete ui;
}

//添加定时器事件
void Widget::timerEvent(QTimerEvent * event){

    if(event->timerId() == timerId_1){
        //每隔1秒钟，让label_timer数字增加
        static int num = 1;
        ui->label_timer->setText(QString::number(num++));
    }

    if(event->timerId() == timerId_2){
        static int num2 = 1;
        //每个2秒让lable_timer_per2sec数字增加
        ui->label_timer_per2sec->setText(QString::number(num2++));
    }

}

bool Widget::eventFilter(QObject * obj, QEvent * event){
    if(obj == ui->label){
        if(event->MouseButtonPress == event->type()){
            QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);

            int x = mouseEvent->x();
            int y = mouseEvent->y();

            QString str = QString("事件过滤器，坐标为:[%1,%2]").arg(x).arg(y);

            qDebug() << str;
            return true;
        }
    }

    //其他事件，还是交给父类过滤器
    return QWidget::eventFilter(obj, event);

}
